<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import { initAMap, getLocationInfo, setMarker, getPlaceSearch, getProvinceAndCityByCoords } from '@/utils/gdMapUtils'

let map = null
let marker = null
const mapCenter = ref()
const targetAddress = ref('')
const addressOptions = ref([])
const loading = ref(false)

const emit = defineEmits(['updateAddress']);


onMounted(() => {
  // 在抽屉绘制地图
  getMap()
})

onUnmounted(() => {
  map?.destroy();
});

// 建立地图图层
const getMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "0bb690da56972f9c3afff8a869992a1f"
  }
  getLocationInfo().then(res => {
    mapCenter.value = res.position
    initAMap().then(AMap => {
      map = new AMap.Map("map-container", {
        viewMode: '2D', //默认使用 2D 模式
        zoom: 11, //地图级别
        center: [mapCenter.value.lng, mapCenter.value.lat], // 初始化地图中心点位置, //地图中心点
      });
      // 根据定位做初始标记
      if (marker) {
        map.remove(marker)
      }
      setMarker(mapCenter.value.lng, mapCenter.value.lat).then(marker => {
        marker = marker
        map.add(marker)
      })
      getProvinceAndCityByCoords(mapCenter.value.lng, mapCenter.value.lat).then(res => {
        // 触发父组件传递的事件
        emit('updateAddress', res);
      }).catch(error => {
        console.error('获取省份和城市失败:', error);
      })
    })
  }, error => { alert("获取地理位置信息出错") })
}

// 搜索
const getSearch = (query) => {
  addressOptions.value = []
  if (query === '') return
  getPlaceSearch(query).then(res => {
    loading.value = false;
    addressOptions.value = res.poiList.pois
    console.log(addressOptions.value)
  })
}

const currentSelect = (val) => {
  if (!val) return;
  targetAddress.value = val
  map.setFitView();
  //设置marker
  // 根据定位做初始标记
  if (marker) {
    map.remove(marker)
  }
  setMarker(val.location.lng, val.location.lat).then(marker => {
    marker = marker
    map.add(marker)
  })
  //更新地图中心点
  map.setCenter([val.location.lng, val.location.lat])
  getProvinceAndCityByCoords(val.location.lng, val.location.lat).then(res => {
    // 触发父组件传递的事件
    emit('updateAddress', res);
  }).catch(error => {
    console.error('获取省份和城市失败:', error);
  })


}
</script>

<template>
  <div class="map">
    <div id="map-container">
      <div style="display: flex;justify-content: center;">
        <el-select v-model="targetAddress" placeholder="搜索地址" style="width: 40%; z-index: 100; margin-top: 10px"
          filterable remote :loading="loading" value-key="id" :remote-method="getSearch" @change="currentSelect">
          <el-option v-for="item in addressOptions" :key="item.id" :label="item.name" :value="item">
          </el-option>
        </el-select>
      </div>
    </div>
  </div>

</template>

<style scoped>
.map{
}
#map-container {
  width: 560px;
  height: 550px;
}
</style>
